<?php
// The source code packaged with this file is Free Software, Copyright (C) 2005 by
// Ricardo Galli <gallir at uib dot es>.
// It's licensed under the AFFERO GENERAL PUBLIC LICENSE unless stated otherwise.
// You can get copies of the licenses here:
// 		http://www.affero.org/oagpl.html
// AFFERO GENERAL PUBLIC LICENSE is also included in the file called "COPYING".

include_once('Smarty.class.php');
$main_smarty = new Smarty;

include('config.php');
include(mnminclude.'html1.php');
include(mnminclude.'ts.php');
include(mnminclude.'link.php');
include(mnminclude.'tags.php');
include(mnminclude.'user.php');
include(mnminclude.'smartyvariables.php');

// html tags allowed during submit
$main_smarty->assign('Story_Content_Tags_To_Allow', htmlspecialchars(Story_Content_Tags_To_Allow));

// breadcrumbs and page titles

$navwhere['text1'] = $main_smarty->get_config_vars('PLIGG_Visual_Breadcrumb_Submit');
$navwhere['link1'] = getmyurl('submit', '');
$main_smarty->assign('navbar_where', $navwhere);
$main_smarty->assign('posttitle', " / " . $main_smarty->get_config_vars('PLIGG_Visual_Breadcrumb_Submit'));

$main_smarty = do_sidebar($main_smarty);

// make sure user is logged in
force_authentication();

// module system hook
$vars = '';
check_actions('submit_post_authentication', $vars);

// this is for direct links from weblogs
if(empty($_POST['phase']) && !empty($_GET['url'])) {
	$_POST['phase'] = 1;
	$_POST['submit_url'] = $_GET['url'];
	$_POST['randkey'] = rand(10000,10000000);
	if(!empty($_GET['trackback'])) 
	$_POST['trackback'] = $_GET['trackback'];
}

// determine which step of the submit process we are on
if(isset($_POST["phase"])) {
	$phase = $_POST["phase"]; 
} 
else {
	$phase = 0;
}

define('pagename', 'submit_thing'); 
$main_smarty->assign('pagename', pagename);

if (isset($_REQUEST['group'])) {
	$main_smarty->assign('group',$_REQUEST['group']);
}
else {
	$main_smarty->assign('group',0);
}

switch ($phase) {
	case 0:
		do_submit0();
		break;
	case 1:
		do_submit1();
		break;
	case 2:
		do_submit2();
		break;
}

exit;

// prepare the submit thing form
function do_submit0() {
	global $main_smarty, $the_template;
	getgroup();
	if (!isset($_POST['submit_url']) || ($_POST['submit_url'] == '')) {
		$submit_url = 'http://';
	}
	if (isset($_GET['owner'])) {
		$owner = $_GET['owner'];
	}
	else {
		$owner = 0;
	}
	
	$main_smarty->assign('alreadydigg','true');
	$main_smarty->assign('submit_url',$submit_url);
	$main_smarty->assign('owner',$owner);
	$main_smarty->assign('submit_rand', rand(10000,10000000));
	
	$main_smarty->assign('tpl_center', $the_template . '/submit_thing_step_1');
	$vars = '';
	check_actions('do_submit0', $vars);
	$main_smarty->display($the_template . '/pligg.tpl');
}

// submit thing insert into table, and add owner if it already has one
function do_submit1() {
	global $main_smarty, $db, $dblang, $current_user, $the_template, $top_users_size, $reco_offset, $reco_rows;

	$submit_url = htmlspecialchars(strip_tags(trim($_POST['submit_url'])));
	$submit_url = str_replace('&amp;', '&', $submit_url);  
	$submit_url = html_entity_decode($submit_url);
	//$url_is_valid = check_url($submit_url);
	$url_is_valid = $_POST['url_is_valid'];
	$trackback = strip_tags(trim($_POST['trackback']));
	$submit_rand = $_POST['randkey'];
	//if (($url_is_valid) && ($trackback == '')) {$trackback = get_trackback_from_url($submit_url);}

	$main_smarty->assign('urlcheck',$_POST['urlcheck']);
	if (($_POST['submit_url'] == '') ||($_POST['submit_url'] == 'http://')||(($_POST['title'] == '') && ($_POST['alreadydigg'] == 'false')) || ($_POST['desc'] == '') || ($url_is_valid == 'false') ) {//invalid input, get back
		if (($_POST['submit_url'] == '') || ($_POST['submit_url'] == 'http://')) {
			$main_smarty->assign('urlcheck','请输入url');
		}
		if (!$url_is_valid) {
			$main_smarty->assign('urlcheck','请输入可访问的url');
		}
		if (($_POST['title'] == '') && ($_POST['alreadydigg'] == 'false')) {
			$main_smarty->assign('titlecheck','请输入标题');
		}
		if ($_POST['desc'] == '') {
			$main_smarty->assign('desccheck','请输入评论');
		}
		
		$main_smarty->assign('submit_url', $_POST['submit_url']);
		$main_smarty->assign('trackback', $gettrackback);
		$main_smarty->assign('tags', $_POST['tags']);
		$main_smarty->assign('title', $_POST['title']);
		$main_smarty->assign('desc', $_POST['desc']);
		$main_smarty->assign('randkey', $_POST['randkey']);	
		$main_smarty->assign('owner', $_POST['owner']);	
		$main_smarty->assign('alreadydigg', $_POST['alreadydigg']);	
		
		$main_smarty->assign('tpl_center', $the_template . '/submit_thing_step_1');
		check_actions('do_submit0', $vars);
		$main_smarty->display($the_template . '/pligg.tpl');
		return ;
	}
	
	$cid = 0;
	$todigglink = new Link();
	//$todigglink->url = $submit_url;
	$todigglink->url = $_POST['submit_url'];
	$todigglink->randkey = $_POST['randkey'];
	//$todigglink->get($todigglink->url);
	$todigglink->valid = true;
	if ($todigglink->duplicates($submit_url) == 0) {
		$todigglink->category = get_category_id("物");
		$todigglink->status='published';
		$todigglink->published_date = time();
		$todigglink->author=$current_user->user_id;
		$todigglink->title = strip_tags(trim($_POST['title']));
		$todigglink->title_url = makeUrlFriendly($todigglink->title);
		$todigglink->tags = tags_normalize_string(strip_tags(str_replace('，',',',trim($_POST['tags']))));
		$todigglink->content = strip_tags(trim($_POST['desc']), Story_Content_Tags_To_Allow);
		$todigglink->content = str_replace("\n", "<br />", $todigglink->content);
		$todigglink->link_summary = utf8_substr(strip_tags(trim($_POST['desc']), Story_Content_Tags_To_Allow), 0, StorySummary_ContentTruncate - 1);
		$todigglink->link_summary = str_replace("\n", "<br />", $todigglink->link_summary);		
		//$todigglink->id = 0;
		$todigglink->store();
		totals_adjust_count('published', 1);
		$todigglink->read(FALSE);
		
		tags_insert_string($todigglink->id, $dblang, $todigglink->tags);
	
		if($todigglink->votes($current_user->user_id) == 0 && auto_vote == true) {
			//$todigglink->insert_vote($current_user->user_id, '10');
			$todigglink->insert_vote($current_user->user_id, '10',$_REQUEST['group']);
			$todigglink->store();
			$todigglink->read(FALSE); 
		}
		
		if (strlen($_POST['desc']) > 0) {	
			$cid = add_comment($todigglink->id,rand(10000,10000000),$current_user->user_id,$_POST['desc']);
			$todigglink->adjust_comment(1);
			$todigglink->store();
			$todigglink->read(FALSE); 
		}
	
		$todigglink->date = time();
		$todigglink->published_date = time();
		$todigglink->store();
		
		if ($_POST['owner'] > 0) {
			add_linkowner($todigglink->id, $_POST['owner']);
			header('location: ' . my_base_url . my_pligg_base . '/story.php?title=' . $todigglink->title_url );
		}
		else {//select one user as it's owner
			$checkdiggedlinkurl = my_base_url . my_pligg_base . '/story.php?title=' . $todigglink->title_url;
			$createownerurl = my_base_url . my_pligg_base . '/submit_user.php?lid=' . $todigglink->id;
			$diggedlinkid = $todigglink->id;
			$noresult = 'true';
			$main_smarty->assign('checkdiggedlinkurl',$checkdiggedlinkurl);
			$main_smarty->assign('createownerurl',$createownerurl);
			$main_smarty->assign('diggedlinkid',$diggedlinkid);
			$main_smarty->assign('noresult',$noresult);
			
			$main_smarty->assign('reco_cur_page',1);
			$reco_offset = 0;
			//$reco_sqlquery = "SELECT count(*) FROM " . table_links . ", " . table_votes . " WHERE vote_user_id=$current_user->user_id AND vote_link_id=link_id AND vote_value > 0 AND link_status!='discard' AND link_category=" . get_category_id('人');
			$reco_sqlquery = "SELECT COUNT(DISTINCT " . table_users . ".user_id)" . " FROM " . table_links . ", " . table_votes . ", " . table_link_owner . ", " . table_users . " WHERE " . table_votes. ".vote_user_id=" .$current_user->user_id . " AND " . table_votes . ".vote_link_id=" . table_links . ".link_id AND " . table_links . ".link_id=" . table_link_owner . ".link_id AND " . table_votes .  ".vote_value > 0  AND " . table_users . ".user_id=" . table_link_owner . ".owner_id" . " AND " .table_links . ".link_category=" . get_category_id("人") . " AND " . table_links . ".link_status!='discard'";
			$reco_rows = $db->get_var($reco_sqlquery);
			//echo "reco_sqlquery:" . $reco_sqlquery;
			//echo "reco_rows:" . $reco_rows;
			if ($reco_rows > 0) {
				$main_smarty->assign('norecouser', 'false');
				//$reco_sqlquery = "SELECT DISTINCT " . table_link_owner . ".owner_id FROM " . table_links . ", " . table_votes . ", " . table_link_owner . " WHERE " . table_votes. ".vote_user_id=" .$current_user->user_id . " AND " . table_votes . ".vote_link_id=" . table_links . ".link_id AND " .table_votes .  ".vote_value > 0  AND " . table_links . ".link_status!='discard' ORDER BY " . table_links . ".link_date DESC LIMIT $reco_offset,$top_users_size";
				$reco_sqlquery = "SELECT DISTINCT " . table_users . ".user_id," . table_users . ".user_login," . table_users . ".user_names" ." FROM " . table_links . ", " . table_votes . ", " . table_link_owner . ", " . table_users . " WHERE " . table_votes. ".vote_user_id=" .$current_user->user_id . " AND " . table_votes . ".vote_link_id=" . table_links . ".link_id AND " . table_links . ".link_id=" . table_link_owner . ".link_id AND " . table_votes .  ".vote_value > 0  AND " . table_users . ".user_id=" . table_link_owner . ".owner_id" . " AND " .table_links . ".link_category=" . get_category_id("人") . " AND " . table_links . ".link_status!='discard' ORDER BY " . table_links . ".link_date DESC LIMIT $reco_offset,$top_users_size";
				$reco_searchsql = mysql_query($reco_sqlquery);
				$reco_userlist = array();
				while ($row = mysql_fetch_array ($reco_searchsql, MYSQL_ASSOC)) array_push ($reco_userlist, $row);
				foreach($reco_userlist as $key => $val){
						$reco_userlist[$key]['Avatar'] = get_avatar('large', "", $val['user_login'], $val['user_email']);
				}
				$main_smarty->assign('reco_userlist', $reco_userlist);
				//echo 'reco_sqlquery:' . $reco_sqlquery;
				//echo 'array_count_values():' . array_count_values($reco_userlist);
			}
			else {
				$main_smarty->assign('norecouser', 'true');
			}
			
			$main_smarty->assign('tpl_center', $the_template . '/submit_thing_step_2');
			$main_smarty->display($the_template . '/pligg.tpl');
		}
	}
	else {//duplicate url
		$todigglink->id = $db->get_var("SELECT link_id FROM " . table_links . " WHERE link_url='". $submit_url . "'" . "AND link_status != 'discard'" );
		$todigglink->read();
		if (strlen($_POST['desc']) > 0) {	
			$cid = add_comment($todigglink->id,rand(10000,10000000),$current_user->user_id,$_POST['title'] . ' ' . $_POST['desc']);
			$todigglink->adjust_comment(1);
			if($todigglink->votes($current_user->user_id) == 0) {
				$todigglink->insert_vote($current_user->user_id, '10');
			}
			$todigglink->store();
			$todigglink->read(FALSE); 
		}

		header('location: ' . my_base_url . my_pligg_base . '/story.php?title=' . $todigglink->title_url . '#c' . $cid);
	}
}

// set the thing's owner
function do_submit2() {
	if ($_POST['action'] == 'searchuser') {
		global $offset, $rows, $reco_offset, $reco_rows, $page_size, $top_users_size, $main_smarty, $db, $dblang, $current_user, $the_template;

		$main_smarty->assign('checkdiggedlinkurl',$_POST['checkdiggedlinkurl']);
		$main_smarty->assign('createownerurl',$_POST['createownerurl']);
		$main_smarty->assign('diggedlinkid',$_POST['diggedlinkid']);
		$main_smarty->assign('norecouser',$_POST['norecouser']);
		if ($_POST['norecouser'] == 'false') {
			$main_smarty->assign('reco_cur_page',reco_get_current_page());
			$reco_offset=(reco_get_current_page()-1)*$top_users_size;
			$reco_sqlquery = "SELECT COUNT(DISTINCT " . table_users . ".user_id)" . " FROM " . table_links . ", " . table_votes . ", " . table_link_owner . ", " . table_users . " WHERE " . table_votes. ".vote_user_id=" .$current_user->user_id . " AND " . table_votes . ".vote_link_id=" . table_links . ".link_id AND " . table_links . ".link_id=" . table_link_owner . ".link_id AND " . table_votes .  ".vote_value > 0  AND " . table_users . ".user_id=" . table_link_owner . ".owner_id" . " AND " .table_links . ".link_category=" . get_category_id("人") . " AND " . table_links . ".link_status!='discard'";
			$reco_rows = $db->get_var($reco_sqlquery);
			$reco_sqlquery = "SELECT DISTINCT " . table_users . ".user_id," . table_users . ".user_login," . table_users . ".user_names" ." FROM " . table_links . ", " . table_votes . ", " . table_link_owner . ", " . table_users . " WHERE " . table_votes. ".vote_user_id=" .$current_user->user_id . " AND " . table_votes . ".vote_link_id=" . table_links . ".link_id AND " . table_links . ".link_id=" . table_link_owner . ".link_id AND " . table_votes .  ".vote_value > 0  AND " . table_users . ".user_id=" . table_link_owner . ".owner_id" . " AND " .table_links . ".link_category=" . get_category_id("人") . " AND " . table_links . ".link_status!='discard' ORDER BY " . table_links . ".link_date DESC LIMIT $reco_offset,$top_users_size";
			$reco_searchsql = mysql_query($reco_sqlquery);
			$reco_userlist = array();
			while ($row = mysql_fetch_array ($reco_searchsql, MYSQL_ASSOC)) array_push ($reco_userlist, $row);
			foreach($reco_userlist as $key => $val){
				$reco_userlist[$key]['Avatar'] = get_avatar('large', "", $val['user_login'], $val['user_email']);
			}
			$main_smarty->assign('reco_userlist', $reco_userlist);	
		}
		$main_smarty->assign('usernames',$_POST['usernames']);
		$main_smarty->assign('cur_page',get_current_page());//use $_POST['page']
		if (trim($_POST['usernames']) != '') {
			$offset=(get_current_page()-1)*$top_users_size;
			$sqlquery = "SELECT count(*) FROM " . table_users . " where user_login LIKE '%".$_POST["usernames"]."%' OR user_names LIKE '%".$_POST["usernames"]."%'";
			$rows = $db->get_var($sqlquery);
			if (!($offset<$rows)) {
				$offset = 0;//in case the user change the keyword to search
				$main_smarty->assign('cur_page',1);
				$_POST['page'] = 1;//so the submit_user_do_page will not get wrong location
			}
			if ($rows>0) {
				$sqlquery = "SELECT * FROM " . table_users . " where user_login LIKE '%".$_POST["usernames"]."%' OR user_names LIKE '%".$_POST["usernames"]."%'";
				$sqlquery = $sqlquery . " LIMIT $offset,$top_users_size";
				$searchsql = mysql_query($sqlquery);
				$userlist = array();
				while ($row = mysql_fetch_array ($searchsql, MYSQL_ASSOC)) array_push ($userlist, $row);
				foreach($userlist as $key => $val){
					$userlist[$key]['Avatar'] = get_avatar('large', "", $val['user_login'], $val['user_email']);
				}
				$main_smarty->assign('userlist', $userlist);
			}	
			else {
				//no such user in the system
				$noresult = 'true';
				$main_smarty->assign('noresult',$noresult);
				$main_smarty->assign('nouserhint','系统中没有此用户');
			}
		}
		if (trim($_POST['usernames']) == '') {
			$noresult = 'true';
			$main_smarty->assign('noresult',$noresult);	
		}
		$main_smarty->assign('tpl_center', $the_template . '/submit_thing_step_2');
		$main_smarty->display($the_template . '/pligg.tpl');
		return ;
	}
	if ($_POST['action'] == 'addowner') {
		//insert owner
		add_linkowner($_POST['diggedlinkid'], $_POST['owner']);
		header('location: ' . $_POST['checkdiggedlinkurl']);
	}
}
?>
